<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-6-18
 * Time: 上午9:43
 * @author 郑钟良<zzl@ourstu.com>
 */

namespace Addons\Consult\Controller;


use Admin\Builder\AdminConfigBuilder;
use Admin\Builder\AdminListBuilder;
use Admin\Controller\AddonsController;

class AdminController extends AddonsController{

    protected $consultCategoryModel;
    protected $consultModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->consultCategoryModel=D('Addons://Consult/ConsultCategory');
        $this->consultModel=D('Addons://Consult/Consult');
    }

    public function buildList($page=1,$r=20)
    {
        $aUseSpace=I('use_space','','text');
        if($aUseSpace!=''){
            $map['table_name']=$aUseSpace;
        }
        $aCategory=I('category',0,'intval');
        if($aCategory){
            $map['type_id']=$aCategory;
        }
        $map_category['status']=array('egt',0);
        $category_options_list=$this->consultCategoryModel->getList(array('status'=>array('egt',0)));
        $category_options=array(0=>array('id'=>0,'value'=>'全部'));
        foreach($category_options_list as $val){
            $one_option['id']=$val['id'];
            $one_option['value']=$val['title'];
            $category_options[]=$one_option;
        }

        $use_space_options_list=$this->_getAddonsConfig('use_space');
        $use_space_options=array(0=>array('id'=>'','value'=>'全部'));
        foreach($use_space_options_list as $key=>$val){
            $one_option['id']=$key;
            $one_option['value']=$val;
            $use_space_options[]=$one_option;
        }
        //dump($use_space_options);exit;
        $map['status']=array('egt',0);
        list($list,$totalCount)=$this->consultModel->getList($map,'id desc',$r,$page);
        $builder=new AdminListBuilder();
        $builder->title('咨询列表')
            ->setSelectPostUrl(addons_url('Consult://Admin/buildList'))
            ->select('','use_space','select','','','',$use_space_options)
            ->select('','category','select','','','',$category_options)
            ->button('分类管理',array('href'=>addons_url('Consult://Admin/category')))
            ->setStatusUrl(addons_url('Consult://Admin/setStatus'))
            ->buttonEnable()->buttonDisable()->buttonDelete()
            ->keyId()
            ->keyUid()
            ->keyText('content','咨询内容')
            ->keyText('answer','回复内容')
            ->keyUid('answer_uid','回答者')
            ->keyUpdateTime('update_time','回复时间')
            ->keyCreateTime()
            ->keyStatus()
            ->keyDoActionEdit('admin/addons/execute?_addons=consult&_controller=admin&_action=edit&id=###')
            ->data($list)
            ->pagination($totalCount,$r);
        $builder->display();
    }

    public function edit()
    {
        if(IS_POST){
            $data['id']=I('post.id',0,'intval');

            $consult=$this->consultModel->getData($data['id']);

            $data['type_id']=I('post.type_id',0,'intval');
            $data['content']=I('post.content','','text');
            $data['answer']=I('post.answer','','text');
            $data['update_time']=I('post.update_time',time(),'intval');
            $data['create_time']=I('post.create_time',time(),'intval');
            $data['status']=I('post.status',1,'intval');
            $data['table_name']=I('post.table_name','','text');
            $data['row_id']=I('post.row_id',0,'intval');
            $res=$this->consultModel->editData($data);
            if($res){

                if($data['status']==1&&mb_strlen($consult['answer'],'utf-8')==0&&mb_strlen($data['answer'],'utf-8')>0){
                    $title = get_nickname(rget_uid())." 回复咨询";
                    $message = '咨询内容：' . $consult['content'].'<br/>回复内容：'.$data['answer'];
                    D('Common/Message')->sendMessage(get_uid(), $title, $message, $consult['from_url'], null, $consult['uid'],1);
                }

                $this->success('操作成功！');
            }else{
                $this->error('操作失败！'.$this->getError());
            }
        }else{
            $aId=I('id',0,'intval');
            $data=$this->consultModel->getData($aId);
            if($aId){
                $category_list=$this->consultCategoryModel->getList(array('use_space'=>array('like',array('%['.$data['table_name'].']%','')),'status'=>1));
            }else{
                $category_list=$this->consultCategoryModel->getList(array('status'=>1));
            }
            $options=array();
            foreach($category_list as $val){
                $options[$val['id']]=$val['title'];
            }
            $builder=new AdminConfigBuilder();
            $builder->title('编辑咨询')
                ->data($data)
                ->keyId()
                ->keyUid('uid','咨询者id')
                ->keySelect('type_id','所属类型','',$options)
                ->keyTextArea('content','咨询内容')
                ->keyTextArea('answer','回复内容')
                ->keyUpdateTime('update_time','回复时间')
                ->keyStatus()
                ->keyText('table_name','数据表名')
                ->keyText('row_id','行号')
                ->keyCreateTime()
                ->buttonSubmit()->buttonBack()
                ->display();
        }
    }

    public function setStatus()
    {
        $ids=I('ids');
        !is_array($ids)&&$ids=explode(',',$ids);
        $status=I('status',1,'intval');
        $builder=new AdminListBuilder();
        $builder->doSetStatus('Consult',$ids,$status);
    }

    public function category()
    {
        $map['status']=array('egt',0);
        $list=$this->consultCategoryModel->getList($map);
        $builder=new AdminListBuilder();
        $builder->title('咨询分类列表')
            ->buttonNew(addons_url('Consult://Admin/editCategory'))
            ->setStatusUrl(addons_url('Consult://Admin/setCategoryStatus'))
            ->buttonEnable()->buttonDisable()->buttonDelete()
            ->keyId()
            ->keyTitle()
            ->keyText('use_space','使用范围')
            ->keyText('tip','提示语')
            ->keyText('sort','排序')
            ->keyStatus()
            ->keyDoActionEdit('admin/addons/execute?_addons=consult&_controller=admin&_action=editcategory&id=###')
            ->data($list)
            ->display();
    }

    public function editCategory()
    {
        $aId=I('id',0,'intval');
        $title=$aId?"编辑":"新增";
        if(IS_POST){
            $data['title']=I('post.title','','text');
            if(mb_strlen($data['title'],'utf-8')<=0){
                $this->error('标题不能为空！');
            }
            $data['use_space']=I('post.use_space','','text');
            $data['use_space']=explode(',',$data['use_space']);
            foreach($data['use_space'] as &$val){
                if($val){
                    $val='['.$val.']';
                }
            }
            unset($val);
            $data['use_space']=implode(',',$data['use_space']);
            $data['tip']=I('post.tip','','text');
            $data['sort']=I('post.sort',0,'intval');
            $data['status']=I('post.status',1,'intval');

            if($aId){
                $data['id']=$aId;
            }
            $res=$this->consultCategoryModel->editData($data);
            if($res){
                $this->success("{$title}成功！");
            }else{
                $this->error("{$title}失败！".$this->consultCategoryModel->getError());
            }
        }else{
            if($aId){
                $data=$this->consultCategoryModel->getData($aId);
            }
            $options=$this->_getAddonsConfig('use_space');
            $builder=new AdminConfigBuilder();
            $builder->title("{$title}咨询分类")
                ->data($data)
                ->keyId()
                ->keyTitle()
                ->keyCheckBox('use_space','使用范围','不选的话代表全部',$options)
                ->keyTextArea('tip','提示信息')
                ->keyInteger('sort','排序')
                ->keyStatus()->keyDefault('status',1)
                ->buttonSubmit()->buttonBack()
                ->display();
        }
    }

    public function setCategoryStatus($ids)
    {
        $status=I('get.status',1,'intval');
        $ids=I('ids');
        !is_array($ids)&&$ids=explode(',',$ids);
        $builder=new AdminListBuilder();
        $builder->doSetStatus('ConsultCategory',$ids,$status);
    }

    private function _getAddonsConfig($name='')
    {
        $config=S('CONSULT_ADDONS_CONFIG');
        if(!$config){
            $map['name']    =   "Consult";
            $map['status']  =   1;
            $config  =   M('Addons')->where($map)->getField('config');
            $config=json_decode($config,true);

            $use_space = str_replace("\r", '', $config['use_space']);
            $use_space = explode("\n", $use_space);
            $config['use_space']=array();
            foreach ($use_space as &$v) {
                $temp = explode(':', $v);
                $config['use_space'][$temp[0]] = $temp[1];
            }

            S('CONSULT_ADDONS_CONFIG',$config);
        }
        if($name!=''){
            return $config[$name];
        }
        return $config;
    }

} 